var Poker = require('../Poker/Poker');
var PokerRoom = require('../Poker/room').PokerRoom;
var pomelo = require('pomelo');
//var Exchange = require('./exchange')
var Rules = require('./rules');
var gameUtil = require("../../../util/gameUtil");
var RoundStatus = {
    'WAITING': 1,
    'PREPARE': 2,
    'READY': 3,
}

exports.SSZRoom = PokerRoom.extend({
    init: function (rid, creator, msg) {
        msg.options.roomPlayerNum = msg.options.playersNum;
        this._super(rid, creator, msg);

        this._roundStatus = RoundStatus.WAITING;

        this.hasInitZ = false;
        this.guns = [];
        this.isForceQuit = false;
        this.giftcost = 0;
    },
    addGun: function (task) {
        this.guns.push(task);
    },
    getMaxPlayer: function () {
        return this.getSubConfig().roomPlayerNum || this.getOption("playersNum") || 4;
    },
    getRoundInfo: function () {
        var info = this._super();
        info.selectWaitMS = this.getHideOption("selectWaitMS");
        return info;
    },
    // getRoomConfig: function () {
    //     var cfg = this._super();
    //     cfg.destroyWaitTime = 30;
    //     return cfg;
    // },
    onAfterPlayerReady: function (player) {
        this._super(player);

        var playersNum = this.getOption("playersNum");
        if (this.getReadyPlayerCount() >= playersNum) {
            this._startNewRoundAfter(this.getHideOption("startWaitMS"));
        }
    },
    getInfo: function () {
        var info = this._super();
        info.costMode = this.getCostMode();
        if (this.isSceneRoom()) {
            info.rate = this.getSceneConfig().scoreRate;
            info.roundCoin = this.getSceneConfig().roundCoin;
        }
        return info;
    },
    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        if (this.isSceneRoom()) {
            info.rate = this.getSceneConfig().scoreRate;
            info.roundCoin = this.getSceneConfig().roundCoin;
        }
        return info;
    },
    onBeforeStartNewRound: function () {
        this._super();
        if (!this.isSceneRoom()) {
            var nums = this.getOption("playersNum");
            if (!this.hasInitZ) {
                var rand1 = ExNumber.randRange(1, 6);
                var rand2 = ExNumber.randRange(1, 6);
                var randsum = rand1 + rand2;
                this.broadcast('onSZ', {
                    'sz1': rand1,
                    'sz2': rand2,
                });
                if (nums == 2) {
                    if (randsum >= 1 && randsum <= 6) {
                        this._dealerIndex = 1;
                    } else {
                        this._dealerIndex = 2;
                    }
                } else if (nums == 3) {
                    if (randsum >= 1 && randsum <= 4) {
                        this._dealerIndex = 1;
                    } else if (randsum >= 5 && randsum <= 8) {
                        this._dealerIndex = 2;
                    } else {
                        this._dealerIndex = 3;
                    }
                } else if (nums == 4) {
                    if (randsum >= 1 && randsum <= 3) {
                        this._dealerIndex = 1;
                    } else if (randsum >= 4 && randsum <= 6) {
                        this._dealerIndex = 2;
                    } else if (randsum >= 7 && randsum <= 9) {
                        this._dealerIndex = 3;
                    } else {
                        this._dealerIndex = 4;
                    }
                }
                this.hasInitZ = true;
            }
            this.broadcast("onDealerChanged", {
                dealer: this._dealerIndex,
                dealerLZ: this._dealerLZ
            });
            // else {
            //     if ((this._dealerIndex + 1) % (nums + 1) == 0) {
            //         this._dealerIndex = 1;
            //     }
            //     this._dealerIndex = (this._dealerIndex + 1) % (nums + 1);
            //     this.broadcast("onDealerChanged", {
            //         dealer: this._dealerIndex,
            //         dealerLZ: this._dealerLZ
            //     });
            // }
            return;
        }

        //金币场无庄
        this._dealerIndex = 0;
        // var newDealerIndex = 0;
        // //换庄？
        // this.enumPlayers(function (eIndex, ePlayer) {
        //     if (!newDealerIndex && ePlayer.isPlaying()) {
        //         newDealerIndex = eIndex;
        //     }
        // });

        // this._dealerIndex = newDealerIndex;

        // setTimeout(function () {
        //     this.settlementCurRound();
        // }.bind(this), this.getHideOption("selectWaitMS"));
    },
    getSettlementInfo: function () {
        var info = this._super();
        info.guns = this.guns;
        info.ForceSettle = this.isForceQuit;
        return info;
    },
    onAfterStartNewRound: function () {
        this._super();
        this.initPlayersHandCards();

    },
    checkStartNewRound: function () {
        if (this.isPlaying()) {
            return false;
        }
        if (this.isSceneRoom()) {
            var subConfig = this.getSubConfig();
            var temp = this.getPlayerCount();
            if (this.getPlayerCount() == this.getReadyPlayerCount() && this.getReadyPlayerCount() >= this.getSceneConfig().options.roomPlayerNum) {
                return true;
            }
        } else {
            if (this.getReadyPlayerCount() >= this.getMaxPlayer()) {
                return true;
            }
        }

        return false;
    },
    onSettlement: function () {
        this._super();
        //算出总分并分配
        if (this.isForceQuit) {
            return;
        }
        var playerList = [];
        this.enumPlaying(function (eIndex, ePlayer) {
            //ePlayer.settlementPattern();
            playerList.push(ePlayer);
            ePlayer.settleCards = Rules.fomatCards(ePlayer.reciveCards);
            if (!Rules.isStandard(ePlayer.reciveCards)) {
                ePlayer._isStandard = false;
            }
        });
        var len = playerList.length;
        for (var i = 0; i < len; ++i) {
            for (var j = i + 1; j < len; ++j) {
                this._compWiner(playerList[i], playerList[j]);
            }
        }
        //this._compWiner()
        this._sumCount(playerList);
    },
    _sumCount: function (playerList) {
        var comp;
        if (this._isStandardConfig()) {
            var configFS = this.getOption('fanshu');
            if (configFS == 0) {
                comp = this._normalPattern.bind(this, 1);
            } else if (configFS == 1) {
                comp = this._pairPattern.bind(this);
            } else if (configFS == 2) {
                comp = this._threePattern.bind(this);
            } else if (configFS == 3) {
                comp = this._threeTwoPattern.bind(this);
            } else {
                comp = this._normalPattern.bind(this, 1);
            }

        } else {
            console.log('非法设置')
            comp = this._normalPattern.bind(this, 1);
        }
        if (this.isSceneRoom()) {
            comp = this._threeTwoPattern.bind(this);
        }

        var len = playerList.length;
        for (var i = 0; i < len; ++i) {
            for (var j = i + 1; j < len; ++j) {
                comp(playerList[i], playerList[j]);
            }
        }

    },
    _isStandardConfig: function () {
        var playersNum = this.getOption('playersNum');
        var configNum = this.getOption('fanshu');
        if (playersNum == 2 && configNum == 0) {
            return true;
        } else if ((playersNum == 3 && configNum == 1) || (playersNum == 3 && configNum == 0)) {
            return true;
        } else if ((playersNum == 4 && (configNum == 2 || configNum == 3)) || (playersNum == 4 && configNum == 0)) {
            return true;
        }
        return false;
    },
    _pairPattern: function (player1, player2) {

        if (player1.winSum == 2 || player2.winSum == 2) {
            this._normalPattern(2, player1, player2, 2);
        } else {
            this._normalPattern(1, player1, player2);
        }

    },
    _threePattern: function (player1, player2) {
        if (player1.winSum == 3 || player2.winSum == 3) {
            this._normalPattern(2, player1, player2);
        } else {
            this._normalPattern(1, player1, player2, 1);
        }
    },
    _threeTwoPattern: function (player1, player2) {
        if (player1.winSum == 3 || player2.winSum == 3) {
            this._normalPattern(4, player1, player2);
        } else if (player1.winSum == 2 || player2.winSum == 2) {
            this._normalPattern(2, player1, player2);
        } else {
            this._normalPattern(1, player1, player2);
        }
    },
    _storeScores: function (player1, player2, equal, fs, re, long) {
        if (equal) {
            player1.addHeadScore(-2);
            player1.addBodyScore(-4);
            player1.addFootScore(-6);

            player2.addHeadScore(2);
            player2.addBodyScore(4);
            player2.addFootScore(6);

            player1.sendHeadScore(-1);
            player1.sendBodyScore(-2);
            player1.sendFootScore(-3);

            player2.sendHeadScore(1);
            player2.sendBodyScore(2);
            player2.sendFootScore(3);

            if(player1.isDealer() || player2.isDealer()){
                player1.addLongScore(-long);
                player2.addLongScore(long);
                player1.sendLongScore(-long);
                player2.sendLongScore(long);
            }
        } else {
            player1.addHeadScore(-(2 * fs * re['head']));
            player1.addBodyScore(-(2 * fs * re['body']));
            player1.addFootScore(-(2 * fs * re['foot']));


            player2.addHeadScore(2 * fs * re['head']);
            player2.addBodyScore(2 * fs * re['body']);
            player2.addFootScore(2 * fs * re['foot']);


            player1.sendHeadScore(-re['head']);
            player1.sendBodyScore(-re['body']);
            player1.sendFootScore(-re['foot']);


            player2.sendHeadScore(re['head']);
            player2.sendBodyScore(re['body']);
            player2.sendFootScore(re['foot']);

            if(player1.isDealer() ||player2.isDealer()){
                var res = re['head']+re['body'] +re['foot']
                if (res < 0) {
                    player1.addLongScore(long);
                    player1.sendLongScore(long);
                    player2.addLongScore(-long);
                    player2.sendLongScore(-long);

                } else if(res > 0){
                    player1.addLongScore(-long);
                    player1.sendLongScore(-long);
                    player2.addLongScore(long);
                    player2.sendLongScore(long);
                }
            }
        }

    },
    _getlongNum: function () {
        var longSum = this.getOption('headType');
        if (longSum == 0) {
            return 0;
        } else if (longSum == 1) {
            return 2;
        } else if (longSum == 2) {
            return 5
        }
        return 0;
    },
    _normalPattern: function (fs, player1, player2) {
        if (!player1._isStandard && !player2._isStandard) {
            return;
        } else if (!player1._isStandard) {
            var re = Rules.loseAll(Rules.fomatCards(player2.reciveCards), 0);
            this._storeScores(player1, player2, false, fs, re, this._getlongNum());

            var player1Score = (2 * fs - 1) * (re['head'] + re['body'] + re['foot']);
            //var player2Score = -player1Score;

            this.addGun({
                'from': player2.getIndex(),
                'to': player1.getIndex(),
                'score': player1Score
            });

        } else if (!player2._isStandard) {
            var re = Rules.loseAll(Rules.fomatCards(player1.reciveCards), 0);

            this._storeScores(player2, player1, false, fs, re, this._getlongNum());

            var player2Score = (2 * fs - 1) * (re['head'] + re['body'] + re['foot']);
            //var player2Score = -player1Score;
            this.addGun({
                'from': player1.getIndex(),
                'to': player2.getIndex(),
                'score': player2Score
            });
        } else {
            var fomatPlayer1 = Rules.fomatCards(player1.reciveCards);
            var fomatPlayer2 = Rules.fomatCards(player2.reciveCards);

            var re = Rules.compareAll(fomatPlayer1, fomatPlayer2, 0);

            console.log('result')
            console.log(re);
            var gun = Rules.isGun(re);

            if (gun) {
                this._storeScores(player2, player1, false, fs, re, this._getlongNum());
                var player1Score = 0;

                if (re['head'] > 0) {
                    player1Score = (2 * fs - 1) * (re['head'] + re['body'] + re['foot']);

                } else {
                    player1Score = (2 * fs - 1) * (re['head'] + re['body'] + re['foot']);
                }

                var player2Score = -player1Score;
                console.log(player1Score)
                console.log(player2Score)
                if (player1Score > 0) {
                    this.addGun({
                        'from': player1.getIndex(),
                        'to': player2.getIndex(),
                        'score': player1Score
                    });
                } else {
                    this.addGun({
                        'from': player2.getIndex(),
                        'to': player1.getIndex(),
                        'score': player2Score
                    });
                }
                // player1.addGun(player2.getIndex(), player1Score);
                // player2.addGun(player1.getIndex(), player2Score);

            }
            else {
                console.log(re);
                // if (re['head'] == 0 && re['body'] == 0 && re['foot'] == 0) {
                //     console.log('?????')
                //     if (player1.getIndex() == this._dealerIndex) {
                //         console.log('庄家1?')
                //         this._storeScores(player2, player1, true, fs, re, this._getlongNum());
                //
                //         this.addGun({
                //             'from': player1.getIndex(),
                //             'to': player2.getIndex(),
                //             'score': 6
                //         });
                //     }
                //     else if (player2.getIndex() == this._dealerIndex) {
                //         console.log('庄家1?')
                //         this._storeScores(player1, player1, true, fs, re, this._getlongNum());
                //
                //         this.addGun({
                //             'from': player2.getIndex(),
                //             'to': player1.getIndex(),
                //             'score': 6
                //         });
                //     }
                // }
                //this._storeScores(player2,player1,false);
                player2.addHeadScore(-re['head']);
                player2.addBodyScore(-re['body']);
                player2.addFootScore(-re['foot']);
                //player2.addLongScore(-this._getlongNum());


                player1.addHeadScore(re['head']);
                player1.addBodyScore(re['body']);
                player1.addFootScore(re['foot']);
                //  player1.addLongScore(this._getlongNum());

                player2.sendHeadScore(-re['head']);
                player2.sendBodyScore(-re['body']);
                player2.sendFootScore(-re['foot']);
                // player2.sendLongScore(-this._getlongNum());

                player1.sendHeadScore(re['head']);
                player1.sendBodyScore(re['body']);
                player1.sendFootScore(re['foot']);
                //player1.sendLongScore(this._getlongNum());
                if(player1.isDealer() || player2.isDealer()){
                    var res = re['head']+re['body']+re['foot']
                    if (res > 0) {
                        player1.addLongScore(this._getlongNum());
                        player1.sendLongScore(this._getlongNum());
                        player2.addLongScore(-this._getlongNum());
                        player2.sendLongScore(-this._getlongNum());

                    } else if(res < 0){
                        player1.addLongScore(-this._getlongNum());
                        player1.sendLongScore(-this._getlongNum());
                        player2.addLongScore(this._getlongNum());
                        player2.sendLongScore(this._getlongNum());

                    }
                }

            }
        }
    },
    _compWiner: function (player1, player2) {
        if (!player1._isStandard && !player2._isStandard) {
            return;
        } else if (!player1._isStandard) {
            player2.winSum += 1;

        } else if (!player2._isStandard) {
            player1.winSum += 1;
        } else {
            var fomatPlayer1 = Rules.fomatCards(player1.reciveCards);
            var fomatPlayer2 = Rules.fomatCards(player2.reciveCards);

            var re = Rules.compareAll(fomatPlayer1, fomatPlayer2, 0);

            var gun = Rules.isGun(re);

            if (gun) {
                if (re['head'] > 0) {
                    player1.winSum += 1;
                } else {
                    player2.winSum += 1;
                }
            }
        }
    },
    onCurRoundFinished: function () {
        var oldDealerIndex = this.getDealerIndex();
        var newDealerIndex = oldDealerIndex;
        this.enumPlayers(function(eIndex, ePlayer) {
            if (eIndex == oldDealerIndex) {
                if(ePlayer.getSumScore() <= 0){
                    newDealerIndex = this.getNextIndex(oldDealerIndex);
                }
            }
        }.bind(this));
        if (this._dealerIndex != newDealerIndex) {
            this._dealerIndex = newDealerIndex;
            this._dealerLZ = 1;
        } else {
            this._dealerLZ += 1;
        }
        // this.broadcast("onDealerChanged", {
        //     dealer: this._dealerIndex,
        //     dealerLZ: this._dealerLZ
        // });
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        this.guns = [];
        this.isForceQuit = false;
        this.giftcost = 0;
    },
    onPlayerQuitRoom:function(player){
        if (player.getMark('forceQuit')) {
            var sceneConfig = this.getSceneConfig();
            player.alterResourceSync('coin',-sceneConfig.forceQuitCoin);
            this.isForceQuit = true;
            if (!this.isCurRoundFinished()) {
                this.settlementCurRound(0);
            }
        }
    },
    // handleForceQuitRoom: function (player, msg, callback) {
    //     this.isForceQuit = true;
    //     if (!this.isSceneRoom()) {
    //         callback({ code: Code.ROOM_QUIT_FORBIDDEN }); return;
    //     }
    //     callback({})
    //     if (player.isPlaying()) {
    //         this.settlementCurRound();
    //         player.alterResourceSync('coin', -1000);
    //         this._playerQuitRoom(player);
    //     }
    // },
    
    // handleQuitRoom: function (player, msg, callback) {
    //     var code = this.onBeforePlayerQuitRoom(player);
    //     if (code) {
    //         callback({ code: code }); return;
    //     }
    //     callback({

    //     });

    //     this._playerQuitRoom(player);
    // },
    handleEnjoy: function (player, msg, callback) {
        callback({});
        msg.playerIndex = player.getIndex();
        this.broadcast("onRoomChat", msg);
    },
    //预留发送表情消耗钻石功能
    // handleEnjoy: function (player, msg, callback) {
    //     var gameConfig = this.getGameConfig();
    //     var giftType = msg.message.type.id;
    //     var giftConfig = null;
    //     giftConfig = gameConfig.Enjoy[giftType];
    //     var costMode = this.getCostMode();

    //     if (!giftConfig) {
    //         callback({ code: Code.ARGS_VALUE_WRONG }); return;
    //     }
    //     if (!this.giftcost) {
    //         this._canCost();
    //     }
    //     if (costMode == Def.RoomCostMode.CREATOR) {
    //         if (player.uid() == this.getCreator()) {
    //             var cost = ExObject.merge({}, this.giftcost, giftConfig.costs)
    //             if (!player.checkResource(cost)) {
    //                 callback({ code: Code.LACK_OF_RESOURCE }); return;
    //             }
    //             msg.playerIndex = player.getIndex();
    //             this.broadcast("onRoomChat", msg);
    //             player.costResourceSync(giftConfig.costs);
    //             player.alterResource('card',-giftConfig.costs['card']);
    //             callback({});
    //             return;
    //         }
    //         if (!player.checkResource(giftConfig.costs)) {
    //             callback({ code: Code.LACK_OF_RESOURCE }); return;
    //         }
    //         player.costResourceSync(giftConfig.costs);
    //         player.alterResource('card',-giftConfig.costs['card']);
    //         msg.playerIndex = player.getIndex();
    //         this.broadcast("onRoomChat", msg);
    //         callback({});
    //         return;
    //     }
    //     if (costMode == Def.RoomCostMode.WIINER) {
    //         var cost = ExObject.merge({}, this.giftcost, giftConfig.costs)
    //         if (!player.checkResource(cost)) {
    //             callback({ code: Code.LACK_OF_RESOURCE }); return;
    //         }
    //         msg.playerIndex = player.getIndex();
    //         this.broadcast("onRoomChat", msg);
    //         player.costResourceSync(giftConfig.costs);
    //         player.alterResource('card',-giftConfig.costs['card']);
    //         callback({});
    //         return;
    //     }
    //     var cost = ExObject.merge({}, this.giftcost, giftConfig.costs)
    //     if (!player.checkResource(cost)) {
    //         callback({ code: Code.LACK_OF_RESOURCE }); return;
    //     }
    //     msg.playerIndex = player.getIndex();
    //     this.broadcast("onRoomChat", msg);
    //     player.costResourceSync(giftConfig.costs);
    //     player.alterResource('card',-giftConfig.costs['card']);
    //     callback({});
    // },
    _canCost: function () {
        var costMode = this.getCostMode();
        switch (costMode) {
            case Def.RoomCostMode.AA:
                var SubLogic = this.getLogicModule();
                var needResource = gameUtil.calcCreateRoomNeedResource(SubLogic, this.getInitArgs());
                var aaNeedResource = ExObject.mulNew(needResource, 1 / this.getMaxPlayer(), Math.ceil);
                this.giftcost = aaNeedResource;
                break;
            default:
                var NeedResource = gameUtil.calcCreateRoomNeedResource(this.getLogicModule(), this.getInitArgs());
                this.giftcost = NeedResource;
                break;
        }
    },
    //确认亮牌
    handleConfirm: function (player, msg, callback) {
        if (!msg.cards) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        // if (!player.isPlaying()) {
        //     callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        // }

        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.isCurRoundFinished()) {
            callback({ code: Code.ROOM_ROUND_FINISHED }); return;
        }

        var cards = msg.cards;
        if (!ExObject.isObject(cards)) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }

        this.broadcast("onPrepared", {
            playerIndex: player.getIndex(),
        });

        player.setPrepare(cards)
        callback({});

        var isAllPrepare = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isPrepare()) {
                isAllPrepare = false;
            }
        });

        if (isAllPrepare) {
            this.settlementCurRound(500);
        }
    },
    _startNewRoundAfter: function (timeMS) {
        if (this._roundStatus != RoundStatus.WAITING) {
            return;
        }

        this.broadcast("onRoomStartAfter", {
            time: timeMS,
        });

        this._roundStatus = RoundStatus.PREPARE;

        setTimeout(function () {
            if (this._roundStatus != RoundStatus.PREPARE) {
                return;
            }

            this._roundStatus = RoundStatus.READY;
            this.tryStartNewRound();
        }.bind(this), timeMS);
    }
});